package com.example.springboot.util;

import org.apache.lucene.analysis.Analyzer;
import org.apache.lucene.analysis.standard.StandardAnalyzer;
import org.apache.lucene.document.*;
import org.apache.lucene.index.*;
import org.apache.lucene.search.IndexSearcher;
import org.apache.lucene.store.Directory;
import org.apache.lucene.store.FSDirectory;
import org.apache.lucene.util.Version;

import java.io.File;
import java.io.IOException;
import java.nio.file.Paths;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

public class IndexUtil {
    private static Version Lucene_Version = Version.LUCENE_CURRENT;
    private String[] ids = {"1", "2", "3", "4", "5", "6"};
    private String[] emails = {"aa@itat.org", "bb@itat.org", "cc@cc.org", "dd@sina.org", "ee@zttc.edu", "ff@itat.org"};
    private String[] contents = {
            "welcome to visited the space,I like book",
            "hello boy, I like pingpeng ball",
            "my name is cc I like game",
            "I like football",
            "I like football and I like basketball too",
            "I like movie and swim"
    };
    private Date[] dates = null;
    private int[] attachs = {2, 3, 1, 4, 5, 5};
    private String[] names = {"zhangsan", "lisi", "john", "jetty", "mike", "jake"};
    private Directory directory = null;
    private Map<String, Float> scores = new HashMap<String, Float>();
    private DirectoryReader reader = null;
    IndexWriter writer = null;

    private void setDates() {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        try {
            dates = new Date[ids.length];
            dates[0] = sdf.parse("2010-02-19");
            dates[1] = sdf.parse("2012-01-11");
            dates[2] = sdf.parse("2011-09-19");
            dates[3] = sdf.parse("2010-12-22");
            dates[4] = sdf.parse("2012-01-01");
            dates[5] = sdf.parse("2011-05-19");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    //数据初始化
    public IndexUtil() {
        setDates();
        scores.put("itat.org", 2.0f);//设定评分
        scores.put("zttc.edu", 1.5f);
        try {
            directory = FSDirectory.open(new File("E:\\java-source\\lucene\\lucene-index\\2"));
        } catch (IOException e) {
            e.printStackTrace();
        }
        //directory = new RAMDirectory();//创建内存索引
        //index();

    }

    /**
     * 建立索引
     **/
    public void index() {
        IndexWriter writer = null;
        try {
            writer = new IndexWriter(directory, new IndexWriterConfig(Lucene_Version, new StandardAnalyzer(Version.LUCENE_CURRENT)));
            //writer.deleteAll();
            Document doc = null;
            for (int i = 0; i < ids.length; i++) {
                doc = new Document();
                doc.add(new StringField("id", ids[i], Field.Store.YES));
                doc.add(new StringField("email", emails[i], Field.Store.YES));
                doc.add(new TextField("content", contents[i], Field.Store.YES));
                doc.add(new StringField("name", names[i], Field.Store.YES));
                //存储数字
                doc.add(new IntField("attach", attachs[i], Field.Store.YES));
                //存储日期
                doc.add(new LongField("date", dates[i].getTime(), Field.Store.YES));

                String et = emails[i].substring(emails[i].lastIndexOf("@") + 1);
                System.out.println(et);
                /**
                 * 在Lucene4.x中，只能给域加权，不能给文档加权，如果要提高文档的加权，需要给
                 * 文档的每个域进行加权
                 * StringField field = new StringField("newScore", "test", Store.NO);
                 * field.setBoost(2.0f);//设置评分
                 * **/

                writer.addDocument(doc);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (writer != null) writer.close();
            } catch (Exception ex) {
                ex.printStackTrace();
            }
        }
    }


    public static Directory initDirectory(String path) {
        Directory directory = null;
        try {
            directory = FSDirectory.open(new File(path));
        } catch (IOException e) {
            e.printStackTrace();
        }
        return directory;
    }


    public static IndexWriter getIndexWriter(String path) throws IOException {

        IndexWriter indexWriter = null;
        Analyzer analyzer = new StandardAnalyzer(Version.LUCENE_40);
        IndexWriterConfig writerConfig = new IndexWriterConfig(Version.LUCENE_40, analyzer);
        indexWriter = new IndexWriter(initDirectory(path), writerConfig);


        return indexWriter;
    }


    public static IndexWriter getIndexWriter(String indexPath, boolean create) throws IOException {
        Analyzer analyzer = new StandardAnalyzer(Version.LUCENE_40);
        IndexWriterConfig iwc = new IndexWriterConfig(Version.LUCENE_40, analyzer);
        LogMergePolicy mergePolicy = new LogByteSizeMergePolicy();

        //设置segment添加文档(Document)时的合并频率
        // 值较小,建立索引的速度就较慢
        // 值较大,建立索引的速度就较快,>10适合批量建立索引
        mergePolicy.setMergeFactor(50);

        //设置segment最大合并文档(Document)数
        //值较小有利于追加索引的速度
        //值较大,适合批量建立索引和更快的搜索
        mergePolicy.setMaxMergeDocs(5000);

        if (create) {
            iwc.setOpenMode(IndexWriterConfig.OpenMode.CREATE);
        } else {
            iwc.setOpenMode(IndexWriterConfig.OpenMode.CREATE_OR_APPEND);
        }
        IndexWriter writer = new IndexWriter(initDirectory(indexPath), iwc);

        return writer;
    }


    public static IndexSearcher getIndexSearcher(String path) throws IOException {
        IndexSearcher indexSearcher = null;

        IndexReader reader = DirectoryReader.open(initDirectory(path));
        indexSearcher = new IndexSearcher(reader);


        return indexSearcher;
    }
}